﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace DataModel
{
    public class GetService<T>
    {
        public GetService(string URI, Func<CustomBinding, EndpointAddress, T> F, BindingElement PollingDuplexElement = null)
        {
            this.URI = URI;
            this.F = F;
            this.PollingDuplexElement = PollingDuplexElement;
        }
        string URI;
        Func<CustomBinding, EndpointAddress, T> F;

        BindingElement PollingDuplexElement;

        private T _value;
        public T Value
        {
            get
            {
                try
                {
                    if (_value != null)
                    {
                        return _value;
                    }
                    else
                    {
                        var Root = System.Windows.Application.Current.Host.Source.AbsoluteUri;
                        //Root = Root.Replace("http://", "https://");
                        Uri U = new Uri(new Uri(Root), URI);

                        BinaryMessageEncodingBindingElement binary = new BinaryMessageEncodingBindingElement();
                        HttpTransportBindingElement transport;
                        if (U.Scheme == "http")
                            transport = new HttpTransportBindingElement();
                        else if (U.Scheme == "https")
                            transport = new HttpsTransportBindingElement();
                        else
                            throw new Exception(U.Scheme + " is not a recognised URI scheme");
                        transport.MaxBufferSize = int.MaxValue;
                        transport.MaxReceivedMessageSize = transport.MaxBufferSize;

                        CustomBinding binding;
                        if (PollingDuplexElement == null)//We do not need Polling Duplex
                            binding = new CustomBinding(binary, transport);
                        else
                            binding = new CustomBinding(PollingDuplexElement, binary, transport);


                        EndpointAddress address = new EndpointAddress(U, null);

                        _value = F(binding, address);
                        return _value;
                    }
                }
                catch (Exception)
                {
                    return default(T);
                }

            }
        }
    }

    
}
